package com.c212.manager.aspect;

import com.c212.manager.bean.UserInfoEntity;
import com.c212.manager.constants.Consts;
import com.c212.manager.exception.AuthException;
import com.c212.manager.utils.UserContext;
import com.c212.manager.utils.annotation.NotLogin;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//@Aspect
//@Order(1)
//@Component
public class AuthAspect {

    private final static Logger logger = LoggerFactory.getLogger(AuthAspect.class);

    @Pointcut("execution(public * com.c212.manager.controller.*.*(..))" +
            "&& !execution(public * com.c212.manager.controller.UserController.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws Exception {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info("url={}", request.getRequestURL());
        logger.info("method={}", request.getMethod());
        logger.info("ip={}", request.getRemoteAddr());
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        UserInfoEntity sessionUser = (UserInfoEntity) request.getSession().getAttribute(Consts.USER_SESSION);
        if (sessionUser == null) {
            logger.warn("【登录校验】Session中没有登录信息");
            throw new AuthException();
        } else {
            UserContext.setUser(sessionUser);
        }
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) throws JsonProcessingException {
        UserContext.remove();
        //logger.info("response={}", new ObjectMapper().writeValueAsString(object));
    }
}
